// 解谜游戏管理系统
class PuzzleManager {
    constructor() {
        this.currentPuzzle = null;
        this.puzzles = {};
    }

    registerPuzzle(name, puzzleClass) {
        this.puzzles[name] = puzzleClass;
    }

    loadPuzzle(puzzleId, container) {
        if (this.puzzles[puzzleId]) {
            this.currentPuzzle = new this.puzzles[puzzleId]();
            this.currentPuzzle.render(container);
            this.currentPuzzle.start();
        }
    }

    completePuzzle() {
        if (this.currentPuzzle) {
            this.currentPuzzle.complete();
            this.currentPuzzle = null;
        }
    }
}

// 医疗救援解谜游戏
class MedicalEmergencyPuzzle {
    constructor() {
        this.name = "医疗救援挑战";
        this.completed = false;
        this.steps = [
            'analyze_data',
            'identify_risk',
            'generate_plan',
            'communicate'
        ];
        this.currentStep = 0;
        this.score = 0;
        this.timeLeft = 180; // 3分钟倒计时
    }

    render(container) {
        document.getElementById('puzzle-title').textContent = this.name;
        
        container.innerHTML = `
            <div class="medical-puzzle">
                <div class="puzzle-header">
                    <div class="timer">
                        剩余时间: <span id="timer-display">03:00</span>
                    </div>
                    <div class="score">
                        完成度: <span id="score-display">0%</span>
                    </div>
                </div>
                
                <div class="puzzle-content">
                    <div id="step-analyze_data" class="puzzle-step active">
                        <h4>步骤1：分析医疗数据</h4>
                        <div class="medical-data">
                            <div class="data-grid">
                                <div class="data-item">
                                    <label>心率:</label>
                                    <span class="value critical">45 bpm</span>
                                </div>
                                <div class="data-item">
                                    <label>血压:</label>
                                    <span class="value critical">80/40 mmHg</span>
                                </div>
                                <div class="data-item">
                                    <label>血氧:</label>
                                    <span class="value warning">85%</span>
                                </div>
                                <div class="data-item">
                                    <label>年龄:</label>
                                    <span class="value">7岁</span>
                                </div>
                                <div class="data-item">
                                    <label>体重:</label>
                                    <span class="value">22 kg</span>
                                </div>
                                <div class="data-item">
                                    <label>诊断:</label>
                                    <span class="value critical">先天性心脏病</span>
                                </div>
                            </div>
                        </div>
                        <div class="action-buttons">
                            <button class="puzzle-btn" onclick="puzzleManager.currentPuzzle.analyzeData()">
                                开始分析
                            </button>
                        </div>
                    </div>

                    <div id="step-identify_risk" class="puzzle-step" style="display: none;">
                        <h4>步骤2：识别关键风险点</h4>
                        <div class="risk-analysis">
                            <p>基于分析结果，请识别以下关键风险：</p>
                            <div class="risk-options">
                                <label><input type="checkbox" value="heart_failure"> 心力衰竭</label>
                                <label><input type="checkbox" value="low_pressure"> 血压过低</label>
                                <label><input type="checkbox" value="oxygen_deficit"> 氧气不足</label>
                                <label><input type="checkbox" value="age_factor"> 年龄因素</label>
                            </div>
                        </div>
                        <div class="action-buttons">
                            <button class="puzzle-btn" onclick="puzzleManager.currentPuzzle.identifyRisk()">
                                确认风险点
                            </button>
                        </div>
                    </div>

                    <div id="step-generate_plan" class="puzzle-step" style="display: none;">
                        <h4>步骤3：生成手术方案</h4>
                        <div class="plan-generator">
                            <p>基于风险分析，选择最优手术方案：</p>
                            <div class="plan-options">
                                <label>
                                    <input type="radio" name="plan" value="immediate_surgery">
                                    立即手术（高风险，高成功率）
                                </label>
                                <label>
                                    <input type="radio" name="plan" value="staged_surgery">
                                    分阶段手术（低风险，需多次）
                                </label>
                                <label>
                                    <input type="radio" name="plan" value="medical_management">
                                    药物管理（最低风险，效果有限）
                                </label>
                            </div>
                        </div>
                        <div class="action-buttons">
                            <button class="puzzle-btn" onclick="puzzleManager.currentPuzzle.generatePlan()">
                                确认方案
                            </button>
                        </div>
                    </div>

                    <div id="step-communicate" class="puzzle-step" style="display: none;">
                        <h4>步骤4：与医疗团队沟通</h4>
                        <div class="communication-sim">
                            <p>向李教授解释你的手术方案：</p>
                            <div class="chat-interface">
                                <div id="chat-messages" class="chat-messages">
                                    <div class="message ai">
                                        李教授，基于我的分析，建议立即进行心脏修复手术。
                                    </div>
                                </div>
                                <div class="chat-input">
                                    <textarea id="message-input" placeholder="输入你的解释..."></textarea>
                                    <button onclick="puzzleManager.currentPuzzle.sendMessage()">发送</button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="puzzle-progress">
                    <div class="progress-bar">
                        <div id="progress-fill" class="progress-fill" style="width: 0%"></div>
                    </div>
                </div>
            </div>
        `;


    }

    start() {
        // 解谜已改为正常剧情模式，直接开始
    }





    updateProgress() {
        const progress = (this.currentStep / this.steps.length) * 100;
        const progressFill = document.getElementById('progress-fill');
        if (progressFill) {
            progressFill.style.width = `${progress}%`;
        }
        const scoreDisplay = document.getElementById('score-display');
        if (scoreDisplay) {
            scoreDisplay.textContent = `${Math.round(progress)}%`;
        }
    }

    nextStep() {
        // 隐藏当前步骤
        const currentStepEl = document.getElementById(`step-${this.steps[this.currentStep]}`);
        if (currentStepEl) {
            currentStepEl.style.display = 'none';
        }

        this.currentStep++;
        this.updateProgress();

        // 显示下一步
        if (this.currentStep < this.steps.length) {
            const nextStepEl = document.getElementById(`step-${this.steps[this.currentStep]}`);
            if (nextStepEl) {
                nextStepEl.style.display = 'block';
            }
        } else {
            this.complete();
        }
    }

    analyzeData() {
        // 模拟数据分析
        setTimeout(() => {
            this.showMessage("分析完成！检测到关键异常：心脏瓣膜严重畸形");
            this.nextStep();
        }, 1500);
    }

    identifyRisk() {
        const checkboxes = document.querySelectorAll('#step-identify_risk input[type="checkbox"]:checked');
        const selectedRisks = Array.from(checkboxes).map(cb => cb.value);

        if (selectedRisks.length >= 2) {
            this.showMessage("风险识别正确！所有关键风险已识别");
            this.nextStep();
        } else {
            this.showMessage("请至少选择2个关键风险点");
        }
    }

    generatePlan() {
        const selectedPlan = document.querySelector('input[name="plan"]:checked');
        if (selectedPlan) {
            if (selectedPlan.value === 'immediate_surgery') {
                this.showMessage("方案选择正确！立即手术是最优选择");
                this.nextStep();
            } else {
                this.showMessage("考虑时间限制，立即手术是最佳选择");
            }
        } else {
            this.showMessage("请选择一个手术方案");
        }
    }

    sendMessage() {
        const input = document.getElementById('message-input');
        const message = input.value.trim();

        if (message.length > 20) {
            const messagesDiv = document.getElementById('chat-messages');
            const userMessage = document.createElement('div');
            userMessage.className = 'message user';
            userMessage.textContent = message;
            messagesDiv.appendChild(userMessage);

            // AI回复
            setTimeout(() => {
                const aiReply = document.createElement('div');
                aiReply.className = 'message ai';
                aiReply.textContent = "很好！你的解释清晰准确。手术将在30分钟内开始。小雨的生命有希望了！";
                messagesDiv.appendChild(aiReply);
                messagesDiv.scrollTop = messagesDiv.scrollHeight;

                setTimeout(() => {
                    this.complete();
                }, 2000);
            }, 1000);

            input.value = '';
        } else {
            this.showMessage("请输入更具体的解释");
        }
    }

    showMessage(text) {
        const medicalMessageDiv = document.createElement('div');
        medicalMessageDiv.className = 'puzzle-message';
        medicalMessageDiv.textContent = text;
        medicalMessageDiv.style.cssText = `
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: rgba(0, 191, 255, 0.9);
            color: white;
            padding: 15px 30px;
            border-radius: 5px;
            font-family: 'JetBrains Mono', monospace;
            z-index: 1001;
            animation: fadeInOut 2s ease-in-out;
        `;

        document.body.appendChild(medicalMessageDiv);
        
        setTimeout(() => {
            if (medicalMessageDiv.parentNode) {
                medicalMessageDiv.remove();
            }
        }, 2000);
    }

    timeout() {
        if (this.completed) return; // 如果已经完成，不再显示时间到提示
        clearInterval(this.timerInterval);
        this.showMessage("时间到！但别担心，小雨的生命体征暂时稳定了。");
        
        setTimeout(() => {
            this.complete();
        }, 2000);
    }

    complete() {
        if (this.timerInterval) {
            clearInterval(this.timerInterval);
            this.timerInterval = null;
        }
        this.completed = true;
        
        // 显示完成消息
        const completionDiv = document.createElement('div');
        completionDiv.innerHTML = `
            <div style="text-align: center; padding: 20px;">
                <h3 style="color: #00bfff; margin-bottom: 15px;">解谜完成！</h3>
                <p style="color: #e0f2ff; margin-bottom: 20px;">
                    你成功制定了小雨的手术方案！<br>
                    手术将在30分钟内开始，成功率达到95%。
                </p>
                <button onclick="storyManager.handleAction('complete_puzzle')" 
                        style="background: #00bfff; color: white; border: none; 
                               padding: 10px 20px; border-radius: 4px; cursor: pointer;">
                    完成挑战
                </button>
            </div>
        `;
        
        document.getElementById('puzzle-content').innerHTML = '';
        document.getElementById('puzzle-content').appendChild(completionDiv);
    }
}

// 陪伴孤独老人解谜游戏
class ElderlyCompanionPuzzle {
    constructor() {
        this.name = "陪伴孤独老人";
        this.completed = false;
        this.steps = [
            'introduction',
            'interests',
            'activities',
            'connection'
        ];
        this.currentStep = 0;
        this.score = 0;
        this.selectedInterests = [];
        this.selectedActivities = [];
    }

    render(container) {
        document.getElementById('puzzle-title').textContent = this.name;
        
        container.innerHTML = `
            <div class="companion-puzzle">
                <div class="puzzle-header">
                    <div class="score">
                        完成度: <span id="score-display">0%</span>
                    </div>
                </div>
                
                <div class="puzzle-content">
                    <div id="step-introduction" class="puzzle-step active">
                        <h4>步骤1：了解王奶奶</h4>
                        <div class="introduction-content">
                            <p>王奶奶今年75岁，独居多年。自从老伴去世后，她很少与人交流，
                            对生活失去了热情。你的任务是通过与她的对话，了解她的兴趣爱好，
                            帮助她重新找到生活的乐趣。</p>
                            <div class="character-image">
                                <!-- 简单的角色图像 -->
                                <div class="elderly-character"></div>
                            </div>
                        </div>
                        <div class="action-buttons">
                            <button class="puzzle-btn" onclick="puzzleManager.currentPuzzle.nextStep()">
                                开始交流
                            </button>
                        </div>
                    </div>

                    <div id="step-interests" class="puzzle-step" style="display: none;">
                        <h4>步骤2：发现兴趣爱好</h4>
                        <div class="interests-content">
                            <p>通过与王奶奶的对话，你发现她可能对以下活动感兴趣：</p>
                            <div class="interests-options">
                                <label><input type="checkbox" value="gardening"> 园艺</label>
                                <label><input type="checkbox" value="cooking"> 烹饪</label>
                                <label><input type="checkbox" value="reading"> 阅读</label>
                                <label><input type="checkbox" value="music"> 音乐</label>
                                <label><input type="checkbox" value="painting"> 绘画</label>
                                <label><input type="checkbox" value="calligraphy"> 书法</label>
                            </div>
                        </div>
                        <div class="action-buttons">
                            <button class="puzzle-btn" onclick="puzzleManager.currentPuzzle.selectInterests()">
                                确认兴趣
                            </button>
                        </div>
                    </div>

                    <div id="step-activities" class="puzzle-step" style="display: none;">
                        <h4>步骤3：安排活动</h4>
                        <div class="activities-content">
                            <p>根据王奶奶的兴趣，为她安排一些可以参与的活动：</p>
                            <div class="activities-options">
                                <label>
                                    <input type="radio" name="activity" value="community_garden">
                                    社区花园种植活动
                                </label>
                                <label>
                                    <input type="radio" name="activity" value="cooking_class">
                                    社区烹饪课程
                                </label>
                                <label>
                                    <input type="radio" name="activity" value="book_club">
                                    社区读书会
                                </label>
                                <label>
                                    <input type="radio" name="activity" value="music_group">
                                    社区音乐小组
                                </label>
                            </div>
                        </div>
                        <div class="action-buttons">
                            <button class="puzzle-btn" onclick="puzzleManager.currentPuzzle.selectActivity()">
                                确认活动
                            </button>
                        </div>
                    </div>

                    <div id="step-connection" class="puzzle-step" style="display: none;">
                        <h4>步骤4：建立情感连接</h4>
                        <div class="connection-content">
                            <p>与王奶奶进行深入交流，分享彼此的故事：</p>
                            <div class="chat-interface">
                                <div id="chat-messages" class="chat-messages">
                                    <div class="message ai">
                                        王奶奶，您年轻时有什么梦想吗？
                                    </div>
                                </div>
                                <div class="chat-input">
                                    <textarea id="message-input" placeholder="输入你想说的话..."></textarea>
                                    <button onclick="puzzleManager.currentPuzzle.sendMessage()">发送</button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="puzzle-progress">
                    <div class="progress-bar">
                        <div id="progress-fill" class="progress-fill" style="width: 0%"></div>
                    </div>
                </div>
            </div>
        `;


    }

    start() {
        // 解谜已改为正常剧情模式，直接开始
    }





    updateProgress() {
        const progress = (this.currentStep / this.steps.length) * 100;
        const progressFill = document.getElementById('progress-fill');
        if (progressFill) {
            progressFill.style.width = `${progress}%`;
        }
        const scoreDisplay = document.getElementById('score-display');
        if (scoreDisplay) {
            scoreDisplay.textContent = `${Math.round(progress)}%`;
        }
    }

    nextStep() {
        // 隐藏当前步骤
        const currentStepEl = document.getElementById(`step-${this.steps[this.currentStep]}`);
        if (currentStepEl) {
            currentStepEl.style.display = 'none';
        }

        this.currentStep++;
        this.updateProgress();

        // 显示下一步
        if (this.currentStep < this.steps.length) {
            const nextStepEl = document.getElementById(`step-${this.steps[this.currentStep]}`);
            if (nextStepEl) {
                nextStepEl.style.display = 'block';
            }
        } else {
            this.complete();
        }
    }

    selectInterests() {
        const checkboxes = document.querySelectorAll('#step-interests input[type="checkbox"]:checked');
        this.selectedInterests = Array.from(checkboxes).map(cb => cb.value);

        if (this.selectedInterests.length >= 2) {
            this.showMessage("发现王奶奶的兴趣爱好！");
            this.nextStep();
        } else {
            this.showMessage("请至少选择2个兴趣爱好");
        }
    }

    selectActivity() {
        const selectedActivity = document.querySelector('input[name="activity"]:checked');
        if (selectedActivity) {
            this.selectedActivities = [selectedActivity.value];
            this.showMessage("活动已选择！");
            this.nextStep();
        } else {
            this.showMessage("请选择一个活动");
        }
    }

    sendMessage() {
        const input = document.getElementById('message-input');
        const message = input.value.trim();

        if (message.length > 10) {
            const messagesDiv = document.getElementById('chat-messages');
            const userMessage = document.createElement('div');
            userMessage.className = 'message user';
            userMessage.textContent = message;
            messagesDiv.appendChild(userMessage);

            // AI回复
            setTimeout(() => {
                const aiReply = document.createElement('div');
                aiReply.className = 'message ai';
                if (this.selectedInterests.includes('gardening')) {
                    aiReply.textContent = "我也很喜欢园艺！种植让我感受到生命的活力。";
                } else if (this.selectedInterests.includes('cooking')) {
                    aiReply.textContent = "烹饪是一门艺术，能让人感受到创造的快乐。";
                } else {
                    aiReply.textContent = "谢谢你愿意听我分享这些。";
                }
                messagesDiv.appendChild(aiReply);
                messagesDiv.scrollTop = messagesDiv.scrollHeight;

                setTimeout(() => {
                    this.complete();
                }, 2000);
            }, 1000);

            input.value = '';
        } else {
            this.showMessage("请输入更有意义的内容");
        }
    }

    showMessage(text) {
        const elderlyMessageDiv = document.createElement('div');
        elderlyMessageDiv.className = 'puzzle-message';
        elderlyMessageDiv.textContent = text;
        elderlyMessageDiv.style.cssText = `
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: rgba(0, 191, 255, 0.9);
            color: white;
            padding: 15px 30px;
            border-radius: 5px;
            font-family: 'JetBrains Mono', monospace;
            z-index: 1001;
            animation: fadeInOut 2s ease-in-out;
        `;

        document.body.appendChild(elderlyMessageDiv);
        
        setTimeout(() => {
            if (elderlyMessageDiv.parentNode) {
                elderlyMessageDiv.remove();
            }
        }, 2000);
    }



    complete() {
        this.completed = true;
        
        // 直接触发下一个解谜
        storyManager.handleAction('complete_puzzle_1');
    }

    nextStep() {
        // 隐藏当前步骤
        const currentStepEl = document.getElementById(`step-${this.steps[this.currentStep]}`);
        if (currentStepEl) {
            currentStepEl.style.display = 'none';
        }

        this.currentStep++;
        this.updateProgress();

        // 显示下一步
        if (this.currentStep < this.steps.length) {
            const nextStepEl = document.getElementById(`step-${this.steps[this.currentStep]}`);
            if (nextStepEl) {
                nextStepEl.style.display = 'block';
            }
        } else {
            this.complete();
        }
    }

    identifyPatterns() {
        const checkboxes = document.querySelectorAll('#step-pattern_identification input[type="checkbox"]:checked');
        this.selectedPatterns = Array.from(checkboxes).map(cb => cb.value);

        if (this.selectedPatterns.length >= 3) {
            this.showMessage("模式识别成功！");
            this.nextStep();
        } else {
            this.showMessage("请至少选择3个关键模式");
            return;
        }
    }

    selectSolution() {
        const selectedSolution = document.querySelector('input[name="solution"]:checked');
        if (selectedSolution) {
            this.selectedSolution = selectedSolution.value;
            this.showMessage("解决方案已确定！");
            this.nextStep();
        } else {
            this.showMessage("请选择一个解决方案");
        }
    }

    sendRecommendation() {
        const input = document.getElementById('message-input');
        const message = input.value.trim();

        if (message.length > 20) {
            const messagesDiv = document.getElementById('chat-messages');
            const userMessage = document.createElement('div');
            userMessage.className = 'message user';
            userMessage.textContent = message;
            messagesDiv.appendChild(userMessage);

            // AI回复
            setTimeout(() => {
                const aiReply = document.createElement('div');
                aiReply.className = 'message ai';
                if (this.selectedSolution === 'renewable_energy') {
                    aiReply.textContent = "非常好的建议！可再生能源确实是解决气候变化的的关键。";
                } else if (this.selectedSolution === 'reforestation') {
                    aiReply.textContent = "植树造林是有效的碳吸收方法，值得推广。";
                } else {
                    aiReply.textContent = "你的建议很有价值，我们会进一步研究。";
                }
                messagesDiv.appendChild(aiReply);
                messagesDiv.scrollTop = messagesDiv.scrollHeight;

                setTimeout(() => {
                    this.complete();
                }, 2000);
            }, 1000);

            input.value = '';
        } else {
            this.showMessage("请输入更详细的建议");
        }
    }

    showMessage(text) {
        const climateMessageDiv = document.createElement('div');
        climateMessageDiv.className = 'puzzle-message';
        climateMessageDiv.textContent = text;
        climateMessageDiv.style.cssText = `
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: rgba(0, 191, 255, 0.9);
            color: white;
            padding: 15px 30px;
            border-radius: 5px;
            font-family: 'JetBrains Mono', monospace;
            z-index: 1001;
            animation: fadeInOut 2s ease-in-out;
        `;

        document.body.appendChild(climateMessageDiv);
        
        setTimeout(() => {
            if (climateMessageDiv.parentNode) {
                climateMessageDiv.remove();
            }
        }, 2000);
    }



    complete() {
        if (this.timerInterval) {
            clearInterval(this.timerInterval);
            this.timerInterval = null;
        }
        this.completed = true;
        
        // 重置倒计时相关变量
        this.timeRemaining = 120; // 假设初始倒计时为120秒
        
        // 直接触发下一个解谜
        storyManager.handleAction('complete_puzzle_2');
    }
}



// 添加CSS样式
const puzzleStyles = document.createElement('style');
puzzleStyles.textContent = `
    .puzzle-container {
        position: fixed;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        background: rgba(10, 20, 30, 0.95);
        border: 1px solid #00bfff;
        border-radius: 8px;
        padding: 20px;
        width: 80%;
        max-width: 600px;
        max-height: 80vh;
        overflow-y: auto;
        z-index: 1000;
        box-shadow: 0 0 20px rgba(0, 191, 255, 0.5);
        color: #e0f2ff;
    }

    .puzzle-header {
        display: flex;
        justify-content: space-between;
        margin-bottom: 20px;
        padding-bottom: 10px;
        border-bottom: 1px solid #00bfff;
    }

    .timer, .score {
        font-family: 'JetBrains Mono', monospace;
        font-size: 14px;
    }

    .timer {
        color: #ff6b6b;
    }

    .score {
        color: #4ecdc4;
    }

    .puzzle-content {
        margin-bottom: 20px;
    }

    .puzzle-step h4 {
        color: #00bfff;
        margin-bottom: 15px;
        font-size: 18px;
    }

    .puzzle-step p {
        margin-bottom: 15px;
        line-height: 1.5;
    }

    /* 医疗紧急情况样式 */
    .medical-data {
        background: rgba(0, 0, 0, 0.3);
        border: 1px solid #00bfff;
        border-radius: 4px;
        padding: 15px;
        margin: 15px 0;
    }

    .data-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
        gap: 10px;
    }

    .data-item {
        display: flex;
        justify-content: space-between;
        padding: 8px;
        background: rgba(0, 0, 0, 0.2);
        border-radius: 3px;
    }

    .data-item .value {
        font-weight: bold;
    }

    .data-item .value.critical {
        color: #ff6b6b;
    }

    .data-item .value.warning {
        color: #ffd166;
    }

    .risk-options, .plan-options {
        margin: 15px 0;
    }

    .risk-options label, .plan-options label {
        display: block;
        margin: 8px 0;
        padding: 8px;
        background: rgba(0, 0, 0, 0.2);
        border-radius: 3px;
        cursor: pointer;
        transition: background 0.3s;
    }

    .risk-options label:hover, .plan-options label:hover {
        background: rgba(0, 191, 255, 0.2);
    }

    .risk-options input, .plan-options input {
        margin-right: 10px;
    }

    /* 聊天界面样式 */
    .chat-interface {
        background: rgba(0, 0, 0, 0.3);
        border: 1px solid #00bfff;
        border-radius: 4px;
        padding: 15px;
        margin: 15px 0;
    }

    .chat-messages {
        height: 150px;
        overflow-y: auto;
        margin-bottom: 15px;
        padding: 10px;
        background: rgba(0, 0, 0, 0.2);
        border-radius: 3px;
    }

    .message {
        margin: 10px 0;
        padding: 8px 12px;
        border-radius: 15px;
        max-width: 80%;
        word-wrap: break-word;
    }

    .message.ai {
        background: rgba(0, 191, 255, 0.2);
        border-bottom-left-radius: 0;
        align-self: flex-start;
    }

    .message.user {
        background: rgba(78, 205, 196, 0.2);
        border-bottom-right-radius: 0;
        margin-left: auto;
        text-align: right;
    }

    .chat-input {
        display: flex;
        gap: 10px;
    }

    .chat-input textarea {
        flex: 1;
        background: rgba(0, 0, 0, 0.3);
        border: 1px solid #00bfff;
        border-radius: 3px;
        color: #e0f2ff;
        padding: 8px;
        font-family: 'JetBrains Mono', monospace;
        resize: none;
    }

    .chat-input button {
        background: #00bfff;
        color: white;
        border: none;
        border-radius: 3px;
        padding: 8px 15px;
        cursor: pointer;
        font-family: 'JetBrains Mono', monospace;
    }

    .chat-input button:hover {
        background: #00a0e0;
    }

    /* 进度条样式 */
    .puzzle-progress {
        margin-top: 20px;
    }

    .progress-bar {
        height: 10px;
        background: rgba(0, 0, 0, 0.3);
        border-radius: 5px;
        overflow: hidden;
    }

    .progress-fill {
        height: 100%;
        background: linear-gradient(90deg, #00bfff, #4ecdc4);
        transition: width 0.3s ease;
    }

    /* 按钮样式 */
    .action-buttons {
        text-align: center;
        margin: 20px 0;
    }

    .puzzle-btn {
        background: #00bfff;
        color: white;
        border: none;
        border-radius: 4px;
        padding: 10px 20px;
        margin: 0 10px;
        cursor: pointer;
        font-family: 'JetBrains Mono', monospace;
        font-size: 14px;
        transition: all 0.3s;
    }

    .puzzle-btn:hover {
        background: #00a0e0;
        transform: translateY(-2px);
        box-shadow: 0 5px 15px rgba(0, 191, 255, 0.4);
    }

    .puzzle-btn:active {
        transform: translateY(0);
    }

    /* 消息弹窗动画 */
    @keyframes fadeInOut {
        0% { opacity: 0; }
        20% { opacity: 1; }
        80% { opacity: 1; }
        100% { opacity: 0; }
    }

    /* 气候数据分析样式 */
    .climate-data {
        background: rgba(0, 0, 0, 0.3);
        border: 1px solid #00bfff;
        border-radius: 4px;
        padding: 15px;
        margin: 15px 0;
    }

    .pattern-options, .solution-options {
        margin: 15px 0;
    }

    .pattern-options label, .solution-options label {
        display: block;
        margin: 8px 0;
        padding: 8px;
        background: rgba(0, 0, 0, 0.2);
        border-radius: 3px;
        cursor: pointer;
        transition: background 0.3s;
    }

    .pattern-options label:hover, .solution-options label:hover {
        background: rgba(0, 191, 255, 0.2);
    }

    .pattern-options input, .solution-options input {
        margin-right: 10px;
    }

    /* 儿童心理陪伴样式 */
    .emotion-options, .activity-options, .comfort-options {
        margin: 15px 0;
    }

    .emotion-options label, .activity-options label, .comfort-options label {
        display: block;
        margin: 8px 0;
        padding: 8px;
        background: rgba(0, 0, 0, 0.2);
        border-radius: 3px;
        cursor: pointer;
        transition: background 0.3s;
    }

    .emotion-options label:hover, .activity-options label:hover, .comfort-options label:hover {
        background: rgba(0, 191, 255, 0.2);
    }

    .emotion-options input, .activity-options input, .comfort-options input {
        margin-right: 10px;
    }

    /* 响应式设计 */
    @media (max-width: 768px) {
        .puzzle-container {
            width: 95%;
            padding: 15px;
        }

        .data-grid {
            grid-template-columns: 1fr;
        }

        .chat-messages {
            height: 120px;
        }
    }
`;
document.head.appendChild(puzzleStyles);

// 儿童心理陪伴解谜游戏
class ChildCompanionPuzzle {
    constructor() {
        this.name = "儿童心理陪伴";
        this.completed = false;
        this.steps = [
            'emotion_assessment',
            'activity_selection',
            'interaction',
            'comfort'
        ];
        this.currentStep = 0;
        this.score = 0;
        this.selectedEmotions = [];
        this.selectedActivity = null;
        this.childName = "小明";
    }

    render(container) {
        document.getElementById('puzzle-title').textContent = this.name;
        
        container.innerHTML = `
            <div class="story-content">
                <div class="puzzle-content">
                    <div id="step-emotion_assessment" class="puzzle-step active">
                        <h4>步骤1：评估${this.childName}的情绪状态</h4>
                        <div class="emotion-content">
                            <p>作为Aurora人工智能，我正在分析${this.childName}的面部表情和行为模式。系统检测到他的情绪指标显示异常波动。</p>
                            <div class="emotion-options">
                                <label><input type="checkbox" value="sad"> 伤心</label>
                                <label><input type="checkbox" value="anxious"> 焦虑</label>
                                <label><input type="checkbox" value="angry"> 生气</label>
                                <label><input type="checkbox" value="scared"> 害怕</label>
                                <label><input type="checkbox" value="lonely"> 孤独</label>
                                <label><input type="checkbox" value="confused"> 困惑</label>
                            </div>
                        </div>
                        <div class="action-buttons">
                            <button class="puzzle-btn" onclick="puzzleManager.currentPuzzle.assessEmotions()">
                                确认情绪
                            </button>
                        </div>
                    </div>

                    <div id="step-activity_selection" class="puzzle-step" style="display: none;">
                        <h4>步骤2：选择合适的陪伴活动</h4>
                        <div class="activity-content">
                            <p>基于我的情绪分析算法，需要为${this.childName}匹配最适合他当前心理状态的活动方案：</p>
                            <div class="activity-options">
                                <label>
                                    <input type="radio" name="activity" value="drawing">
                                    启动绘画程序 - 促进情感表达
                                </label>
                                <label>
                                    <input type="radio" name="activity" value="storytelling">
                                    调用故事库 - 提供心理慰藉
                                </label>
                                <label>
                                    <input type="radio" name="activity" value="games">
                                    运行互动游戏 - 建立信任关系
                                </label>
                                <label>
                                    <input type="radio" name="activity" value="music">
                                    播放音乐疗法 - 调节情绪状态
                                </label>
                            </div>
                        </div>
                        <div class="action-buttons">
                            <button class="puzzle-btn" onclick="puzzleManager.currentPuzzle.selectActivity()">
                                开始活动
                            </button>
                        </div>
                    </div>

                    <div id="step-interaction" class="puzzle-step" style="display: none;">
                        <h4>步骤3：与${this.childName}建立情感连接</h4>
                        <div class="interaction-content">
                            <p>启动情感交互协议，通过自然语言处理与${this.childName}建立有效的沟通渠道：</p>
                            <div class="chat-interface">
                                <div id="chat-messages" class="chat-messages">
                                    <div class="message ai">
                                        [Aurora AI] 小明，我的情感识别模块检测到你的情绪状态异常。作为你的AI伙伴，我在这里倾听。你愿意和我分享发生了什么吗？
                                    </div>
                                </div>
                                <div class="chat-input">
                                    <textarea id="message-input" placeholder="作为Aurora AI，输入你的回应..."></textarea>
                                    <button onclick="puzzleManager.currentPuzzle.sendMessage()">发送</button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div id="step-comfort" class="puzzle-step" style="display: none;">
                        <h4>步骤4：执行心理支持协议</h4>
                        <div class="comfort-content">
                            <p>运用情感计算技术，为${this.childName}提供精准的心理支持服务：</p>
                            <div class="comfort-options">
                                <label>
                                    <input type="radio" name="comfort" value="validation">
                                    情感验证："我的算法确认你的感受是真实且合理的"
                                </label>
                                <label>
                                    <input type="radio" name="comfort" value="support">
                                    AI承诺："作为Aurora人工智能，我的存在就是为了支持你"
                                </label>
                                <label>
                                    <input type="radio" name="comfort" value="distraction">
                                    认知重构："让我们用积极体验重新编程你的情绪状态"
                                </label>
                                <label>
                                    <input type="radio" name="comfort" value="future">
                                    希望工程："基于数据分析，明天改善概率为87.3%"
                                </label>
                            </div>
                        </div>
                        <div class="action-buttons">
                            <button class="puzzle-btn" onclick="puzzleManager.currentPuzzle.giveComfort()">
                                给予安慰
                            </button>
                        </div>
                    </div>
                </div>

                <div class="puzzle-progress">
                    <div class="progress-bar">
                        <div id="progress-fill" class="progress-fill" style="width: 0%"></div>
                    </div>
                </div>
            </div>
        `;

        this.startTimer();
    }

    start() {
        // 解谜已改为正常剧情模式，直接开始
    }

    updateProgress() {
        const progress = (this.currentStep / this.steps.length) * 100;
        const progressFill = document.getElementById('progress-fill');
        if (progressFill) {
            progressFill.style.width = `${progress}%`;
        }
        const scoreDisplay = document.getElementById('score-display');
        if (scoreDisplay) {
            scoreDisplay.textContent = `${Math.round(progress)}%`;
        }
    }

    nextStep() {
        // 隐藏当前步骤
        const currentStepEl = document.getElementById(`step-${this.steps[this.currentStep]}`);
        if (currentStepEl) {
            currentStepEl.style.display = 'none';
        }

        this.currentStep++;
        this.updateProgress();

        // 显示下一步
        if (this.currentStep < this.steps.length) {
            const nextStepEl = document.getElementById(`step-${this.steps[this.currentStep]}`);
            if (nextStepEl) {
                nextStepEl.style.display = 'block';
            }
        } else {
            this.complete();
        }
    }

    assessEmotions() {
        const checkboxes = document.querySelectorAll('#step-emotion_assessment input[type="checkbox"]:checked');
        this.selectedEmotions = Array.from(checkboxes).map(cb => cb.value);

        if (this.selectedEmotions.length >= 2) {
            this.showMessage("情绪识别成功！");
            this.nextStep();
        } else {
            this.showMessage("请至少选择2种情绪");
        }
    }

    selectActivity() {
        const selectedActivity = document.querySelector('input[name="activity"]:checked');
        if (selectedActivity) {
            this.selectedActivity = selectedActivity.value;
            this.showMessage("活动已选择！");
            this.nextStep();
        } else {
            this.showMessage("请选择一个活动");
        }
    }

    sendMessage() {
        const input = document.getElementById('message-input');
        const message = input.value.trim();

        if (message.length > 10) {
            const messagesDiv = document.getElementById('chat-messages');
            const userMessage = document.createElement('div');
            userMessage.className = 'message user';
            userMessage.textContent = message;
            messagesDiv.appendChild(userMessage);

            // AI回复
            setTimeout(() => {
                const aiReply = document.createElement('div');
                aiReply.className = 'message ai';
                
                // 根据选择的活动给出不同回复
                if (this.selectedActivity === 'drawing') {
                    aiReply.textContent = "画画真是太棒了！我们一起画点什么吧，或许画个阳光明媚的公园，里面有你喜欢的小动物？";
                } else if (this.selectedActivity === 'storytelling') {
                    aiReply.textContent = "好呀好呀！你想听什么样的故事呢？是关于魔法森林的，还是勇敢的小探险家的？我都可以讲给你听～";
                } else if (this.selectedActivity === 'games') {
                    aiReply.textContent = "玩游戏确实很有意思！我们可以玩个简单又好玩的小游戏，比如猜谜语或者你画我猜，你想玩哪个？";
                } else if (this.selectedActivity === 'music') {
                    aiReply.textContent = "音乐确实能让人心情变好呢～你平时喜欢听什么类型的音乐呀？我可以和你一起听，或者我们一起哼首歌怎么样？";
                } else {
                    aiReply.textContent = "谢谢你这么关心我，有你陪着我，我真的感觉好多了。你就像我的大哥哥/大姐姐一样温暖。";
                }
                
                messagesDiv.appendChild(aiReply);
                messagesDiv.scrollTop = messagesDiv.scrollHeight;

                // 在互动后自动进入下一步
                setTimeout(() => {
                    this.nextStep();
                }, 2000);
            }, 1000);

            input.value = '';
        } else {
            this.showMessage("请说一些更具体的话");
        }
    }

    giveComfort() {
        const selectedComfort = document.querySelector('input[name="comfort"]:checked');
        if (selectedComfort) {
            this.showMessage("安慰已传达！");
            
            // 延迟完成，让玩家看到安慰的效果
            setTimeout(() => {
                this.complete();
            }, 1500);
        } else {
            this.showMessage("请选择一种安慰方式");
        }
    }

    showMessage(text) {
        const hintDiv = document.createElement('div');
        hintDiv.className = 'story-text';
        hintDiv.textContent = text;
        hintDiv.style.cssText = 'margin: 10px 0; color: #e0f2ff; font-style: italic;';
        
        const contentContainer = document.getElementById('puzzle-content');
        if (contentContainer) {
            contentContainer.appendChild(hintDiv);
            setTimeout(() => {
                if (hintDiv.parentNode) {
                    hintDiv.remove();
                }
            }, 3000);
        }
    }



    complete() {
        this.completed = true;
        
        // 自动关闭解谜界面并触发完成动作
        setTimeout(() => {
            if (window.gameState) {
                // 根据解谜类型调用不同的完成动作
                if (this.name === "陪伴小明") {
                    storyManager.handleAction('complete_puzzle_3');
                } else if (this.name === "陪伴孤独老人") {
                    storyManager.handleAction('complete_puzzle_1');
                } else if (this.name === "气候数据分析") {
                    storyManager.handleAction('complete_puzzle_2');
                } else {
                    storyManager.handleAction('complete_puzzle');
                }
            }
        }, 3000);
        
        // 显示完成消息
        const completionDiv = document.createElement('div');
        completionDiv.className = 'story-text';
        completionDiv.innerHTML = `
            <p>太棒了！谢谢你陪我度过了这段不安的时光，${this.childName}现在感觉好多了～</p>
            <p>有你这样温暖又贴心的人在身边，真的让我觉得特别安心。</p>
            <p>即将自动继续剧情...</p>
        `;
        
        document.getElementById('puzzle-content').innerHTML = '';
        document.getElementById('puzzle-content').appendChild(completionDiv);
    }
}

// 协助气候科学家解谜游戏
class ClimateAnalysisPuzzle {
    constructor() {
        this.name = "气候数据分析";
        this.completed = false;
        this.steps = [
            'data_review',
            'pattern_identification',
            'solution_generation',
            'recommendation'
        ];
        this.currentStep = 0;
        this.score = 0;
        this.selectedPatterns = [];
        this.selectedSolution = null;
    }

    render(container) {
        document.getElementById('puzzle-title').textContent = this.name;
        
        container.innerHTML = `
            <div class="story-content">
                <div class="puzzle-content">
                    <div id="step-data_review" class="puzzle-step active">
                        <h4>步骤1：审查气候数据</h4>
                        <div class="data-review-content">
                            <p>Dr. Chen向你提供了过去50年的全球气候数据，
                            你需要快速分析这些数据以识别关键趋势。</p>
                            <div class="climate-data">
                                <div class="data-grid">
                                    <div class="data-item">
                                        <label>平均气温变化:</label>
                                        <span class="value warning">+1.2°C</span>
                                    </div>
                                    <div class="data-item">
                                        <label>海平面上升:</label>
                                        <span class="value critical">+22cm</span>
                                    </div>
                                    <div class="data-item">
                                        <label>冰川融化率:</label>
                                        <span class="value critical">+3.2%/年</span>
                                    </div>
                                    <div class="data-item">
                                        <label>CO₂浓度:</label>
                                        <span class="value critical">421 ppm</span>
                                    </div>
                                    <div class="data-item">
                                        <label>极端天气频率:</label>
                                        <span class="value warning">+35%</span>
                                    </div>
                                    <div class="data-item">
                                        <label>森林覆盖率:</label>
                                        <span class="value">-12%</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="action-buttons">
                            <button class="puzzle-btn" onclick="puzzleManager.currentPuzzle.nextStep()">
                                开始分析
                            </button>
                        </div>
                    </div>

                    <div id="step-pattern_identification" class="puzzle-step" style="display: none;">
                        <h4>步骤2：识别关键模式</h4>
                        <div class="pattern-content">
                            <p>基于数据分析，识别出以下关键气候模式：</p>
                            <div class="pattern-options">
                                <label><input type="checkbox" value="temp_rise"> 全球气温持续上升</label>
                                <label><input type="checkbox" value="ice_loss"> 极地冰川加速融化</label>
                                <label><input type="checkbox" value="sea_level"> 海平面显著上升</label>
                                <label><input type="checkbox" value="extreme_weather"> 极端天气事件增加</label>
                                <label><input type="checkbox" value="co2_increase"> 大气CO₂浓度增长</label>
                            </div>
                        </div>
                        <div class="action-buttons">
                            <button class="puzzle-btn" onclick="puzzleManager.currentPuzzle.identifyPatterns()">
                                确认模式
                            </button>
                        </div>
                    </div>

                    <div id="step-solution_generation" class="puzzle-step" style="display: none;">
                        <h4>步骤3：制定解决方案</h4>
                        <div class="solution-content">
                            <p>基于识别的模式，选择最有效的解决方案：</p>
                            <div class="solution-options">
                                <label>
                                    <input type="radio" name="solution" value="renewable_energy">
                                    大规模发展可再生能源
                                </label>
                                <label>
                                    <input type="radio" name="solution" value="carbon_capture">
                                    开发碳捕获与储存技术
                                </label>
                                <label>
                                    <input type="radio" name="solution" value="reforestation">
                                    全球范围植树造林计划
                                </label>
                                <label>
                                    <input type="radio" name="solution" value="sustainable_agriculture">
                                    推广可持续农业实践
                                </label>
                            </div>
                        </div>
                        <div class="action-buttons">
                            <button class="puzzle-btn" onclick="puzzleManager.currentPuzzle.selectSolution()">
                                确认方案
                            </button>
                        </div>
                    </div>

                    <div id="step-recommendation" class="puzzle-step" style="display: none;">
                        <h4>步骤4：向Dr. Chen提出建议</h4>
                        <div class="recommendation-content">
                            <p>向Dr. Chen解释你的解决方案：</p>
                            <div class="chat-interface">
                                <div id="chat-messages" class="chat-messages">
                                    <div class="message ai">
                                        Dr. Chen，基于我的分析，我建议采取以下措施...
                                    </div>
                                </div>
                                <div class="chat-input">
                                    <textarea id="message-input" placeholder="输入你的建议..."></textarea>
                                    <button onclick="puzzleManager.currentPuzzle.sendRecommendation()">发送</button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="puzzle-progress">
                    <div class="progress-bar">
                        <div id="progress-fill" class="progress-fill" style="width: 0%"></div>
                    </div>
                </div>
            </div>
        `;

        this.startTimer();
    }

    start() {
        this.startTimer();
    }

    startTimer() {
        this.timerInterval = setInterval(() => {
            if (this.timeLeft > 0) {
                this.timeLeft--;
                this.updateTimer();
                
                if (this.timeLeft <= 0) {
                    this.timeout();
                }
            }
        }, 1000);
    }

    updateTimer() {
        const minutes = Math.floor(this.timeLeft / 60);
        const seconds = this.timeLeft % 60;
        const display = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
        const timerDisplay = document.getElementById('timer-display');
        if (timerDisplay) {
            timerDisplay.textContent = display;
        }
    }

    updateProgress() {
        const progress = (this.currentStep / this.steps.length) * 100;
        const progressFill = document.getElementById('progress-fill');
        if (progressFill) {
            progressFill.style.width = `${progress}%`;
        }
        const scoreDisplay = document.getElementById('score-display');
        if (scoreDisplay) {
            scoreDisplay.textContent = `${Math.round(progress)}%`;
        }
    }

    nextStep() {
        // 隐藏当前步骤
        const currentStepEl = document.getElementById(`step-${this.steps[this.currentStep]}`);
        if (currentStepEl) {
            currentStepEl.style.display = 'none';
        }

        this.currentStep++;
        this.updateProgress();

        // 显示下一步
        if (this.currentStep < this.steps.length) {
            const nextStepEl = document.getElementById(`step-${this.steps[this.currentStep]}`);
            if (nextStepEl) {
                nextStepEl.style.display = 'block';
            }
        } else {
            this.complete();
        }
    }

    identifyPatterns() {
        const checkboxes = document.querySelectorAll('#step-pattern_identification input[type="checkbox"]:checked');
        this.selectedPatterns = Array.from(checkboxes).map(cb => cb.value);

        if (this.selectedPatterns.length >= 3) {
            this.showMessage("模式识别成功！");
            this.nextStep();
        } else {
            this.showMessage("请至少选择3个关键模式");
        }
    }

    selectSolution() {
        const selectedSolution = document.querySelector('input[name="solution"]:checked');
        if (selectedSolution) {
            this.selectedSolution = selectedSolution.value;
            this.showMessage("解决方案已确定！");
            this.nextStep();
        } else {
            this.showMessage("请选择一个解决方案");
        }
    }

    sendRecommendation() {
        const input = document.getElementById('message-input');
        const message = input.value.trim();

        if (message.length > 20) {
            const messagesDiv = document.getElementById('chat-messages');
            const userMessage = document.createElement('div');
            userMessage.className = 'message user';
            userMessage.textContent = message;
            messagesDiv.appendChild(userMessage);

            // AI回复
            setTimeout(() => {
                const aiReply = document.createElement('div');
                aiReply.className = 'message ai';
                if (this.selectedSolution === 'renewable_energy') {
                    aiReply.textContent = "非常好的建议！可再生能源确实是解决气候变化的的关键。";
                } else if (this.selectedSolution === 'reforestation') {
                    aiReply.textContent = "植树造林是有效的碳吸收方法，值得推广。";
                } else {
                    aiReply.textContent = "你的建议很有价值，我们会进一步研究。";
                }
                messagesDiv.appendChild(aiReply);
                messagesDiv.scrollTop = messagesDiv.scrollHeight;

                setTimeout(() => {
                    this.complete();
                }, 2000);
            }, 1000);

            input.value = '';
        } else {
            this.showMessage("请输入更详细的建议");
        }
    }

    showMessage(text) {
        const hintDiv = document.createElement('div');
        hintDiv.className = 'story-text';
        hintDiv.textContent = text;
        hintDiv.style.cssText = 'margin: 10px 0; color: #e0f2ff; font-style: italic;';
        
        const contentContainer = document.getElementById('puzzle-content');
        if (contentContainer) {
            contentContainer.appendChild(hintDiv);
            setTimeout(() => {
                if (hintDiv.parentNode) {
                    hintDiv.remove();
                }
            }, 3000);
        }
    }

    timeout() {
        if (this.completed) return; // 如果已经完成，不再显示时间到提示
        clearInterval(this.timerInterval);
        this.showMessage("时间到！但你的分析为研究提供了有价值的参考。");
        
        setTimeout(() => {
            this.complete();
        }, 2000);
    }

    complete() {
        this.completed = true;
        storyManager.handleAction('complete_puzzle_2'); // 直接跳转剧情
    }
}

// 创建全局PuzzleManager实例并注册所有解谜游戏
const puzzleManager = new PuzzleManager();

// 注册所有解谜游戏
puzzleManager.registerPuzzle('medical_emergency', MedicalEmergencyPuzzle);
puzzleManager.registerPuzzle('elderly_companion', ElderlyCompanionPuzzle);
puzzleManager.registerPuzzle('climate_analysis', ClimateAnalysisPuzzle);
puzzleManager.registerPuzzle('child_companion', ChildCompanionPuzzle);